#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
API路由模块
提供REST API接口
"""

from fastapi import APIRouter, HTTPException, Query
from typing import List, Optional, Dict, Any
from pydantic import BaseModel
from loguru import logger

# 创建路由器
router = APIRouter()

# 全局数据处理器引用（将在main.py中设置）
data_processor = None

def set_data_processor(processor):
    """设置数据处理器实例"""
    global data_processor
    data_processor = processor

class CoinStatsResponse(BaseModel):
    """币种统计响应模型"""
    coin: str
    timeWindows: Dict[str, Dict[str, Dict[str, float]]]
    lastUpdate: int

class SystemStatsResponse(BaseModel):
    """系统统计响应模型"""
    total_coins: int
    total_records: int
    time_windows: List[str]
    memory_usage: Dict[str, int]

@router.get("/coins", response_model=List[CoinStatsResponse])
async def get_all_coins(
    limit: Optional[int] = Query(100, description="返回币种数量限制"),
    window: Optional[str] = Query("5m", description="排序依据的时间窗口")
):
    """获取所有币种的爆仓统计数据"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    try:
        if limit and limit > 0:
            stats = await data_processor.get_top_coins(limit=limit, window=window)
        else:
            stats = await data_processor.get_all_coins_stats()
        
        return stats
    except Exception as e:
        logger.error(f"获取币种数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取数据失败: {str(e)}")

@router.get("/coins/{coin}", response_model=CoinStatsResponse)
async def get_coin_stats(coin: str):
    """获取指定币种的爆仓统计数据"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    try:
        stats = await data_processor.get_coin_stats(coin.upper())
        if not stats:
            raise HTTPException(status_code=404, detail=f"未找到币种 {coin} 的数据")
        
        return stats
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取币种 {coin} 数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取数据失败: {str(e)}")

@router.get("/coins/top/{limit}", response_model=List[CoinStatsResponse])
async def get_top_coins(
    limit: int,
    window: Optional[str] = Query("5m", description="排序依据的时间窗口")
):
    """获取爆仓量最大的前N个币种"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    if limit <= 0 or limit > 200:
        raise HTTPException(status_code=400, detail="limit必须在1-200之间")
    
    valid_windows = ['1m', '3m', '5m', '10m', '15m', '30m']
    if window not in valid_windows:
        raise HTTPException(status_code=400, detail=f"window必须是以下值之一: {valid_windows}")
    
    try:
        stats = await data_processor.get_top_coins(limit=limit, window=window)
        return stats
    except Exception as e:
        logger.error(f"获取Top {limit} 币种数据失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取数据失败: {str(e)}")

@router.get("/stats/system", response_model=SystemStatsResponse)
async def get_system_stats():
    """获取系统统计信息"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    try:
        stats = await data_processor.get_system_stats()
        return stats
    except Exception as e:
        logger.error(f"获取系统统计失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取统计失败: {str(e)}")

@router.get("/stats/summary")
async def get_summary_stats():
    """获取汇总统计信息"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    try:
        # 获取系统统计
        system_stats = await data_processor.get_system_stats()
        
        # 获取所有币种与Top10（UI仍可用）
        all_coins = await data_processor.get_all_coins_stats()
        top_coins = all_coins[:10]
        
        # 计算总爆仓量（覆盖全部币种，窗口固定 5m）
        total_liquidation = {
            'long_amount': 0,
            'short_amount': 0,
            'total_amount': 0,
            'long_volume': 0,
            'short_volume': 0,
            'total_volume': 0
        }
        
        for coin_data in all_coins:
            window_5m = coin_data.get('timeWindows', {}).get('5m', {})
            if window_5m:
                total_liquidation['long_amount'] += window_5m.get('long', {}).get('amount', 0)
                total_liquidation['short_amount'] += window_5m.get('short', {}).get('amount', 0)
                total_liquidation['total_amount'] += window_5m.get('total', {}).get('amount', 0)
                total_liquidation['long_volume'] += window_5m.get('long', {}).get('volume', 0)
                total_liquidation['short_volume'] += window_5m.get('short', {}).get('volume', 0)
                total_liquidation['total_volume'] += window_5m.get('total', {}).get('volume', 0)
        
        return {
            'system': system_stats,
            'top_coins': top_coins,
            'total_liquidation_5m': total_liquidation
        }
    except Exception as e:
        logger.error(f"获取汇总统计失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取统计失败: {str(e)}")

@router.get("/search")
async def search_coins(
    query: str = Query(..., description="搜索关键词"),
    limit: Optional[int] = Query(20, description="返回结果数量限制")
):
    """搜索币种"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    if not query or len(query.strip()) < 1:
        raise HTTPException(status_code=400, detail="搜索关键词不能为空")
    
    try:
        # 获取所有币种数据
        all_coins = await data_processor.get_all_coins_stats()
        
        # 过滤匹配的币种
        query_upper = query.upper().strip()
        matched_coins = [
            coin for coin in all_coins 
            if query_upper in coin['coin'].upper()
        ]
        
        # 精确匹配优先
        exact_matches = [coin for coin in matched_coins if coin['coin'].upper() == query_upper]
        partial_matches = [coin for coin in matched_coins if coin['coin'].upper() != query_upper]
        
        # 合并结果，精确匹配在前
        results = exact_matches + partial_matches
        
        # 限制返回数量
        if limit and limit > 0:
            results = results[:limit]
        
        return {
            'query': query,
            'total_matches': len(results),
            'coins': results
        }
    except Exception as e:
        logger.error(f"搜索币种失败: {e}")
        raise HTTPException(status_code=500, detail=f"搜索失败: {str(e)}")

@router.get("/liquidations/{coin}")
async def get_liquidation_records(
    coin: str,
    limit: Optional[int] = Query(100, description="返回记录数量限制"),
    min_amount: Optional[float] = Query(0, description="最小爆仓金额筛选")
):
    """获取指定币种的逐笔爆仓记录"""
    if not data_processor:
        raise HTTPException(status_code=500, detail="数据处理器未初始化")
    
    try:
        records = await data_processor.get_liquidation_records(coin.upper(), limit, min_amount)
        return {
            'coin': coin.upper(),
            'total_records': len(records),
            'records': records
        }
    except Exception as e:
        logger.error(f"获取爆仓记录失败: {e}")
        raise HTTPException(status_code=500, detail=f"获取记录失败: {str(e)}")

@router.get("/windows")
async def get_time_windows():
    """获取支持的时间窗口列表"""
    return {
        'windows': [
            {'key': '1m', 'label': '1分钟', 'seconds': 60},
            {'key': '3m', 'label': '3分钟', 'seconds': 180},
            {'key': '5m', 'label': '5分钟', 'seconds': 300},
            {'key': '10m', 'label': '10分钟', 'seconds': 600},
            {'key': '15m', 'label': '15分钟', 'seconds': 900}
        ]
    }